<script setup lang='ts'>
import { FormInstance, FormItemRule } from 'element-plus';
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import{ useTokenStore } from '@/stores/token'
import { useUserStore } from '@/stores/user'
import{ getUserInfoService } from '@/api/user'


const tokenStore = useTokenStore()

const userStore = useUserStore()

const router = useRouter()

type Form = {
    phoneNumber: string,
    password: string
}

type Rules = {
    [K in keyof Form]: Array<FormItemRule>
}

const formInline = reactive<Form>({
    phoneNumber: '',
    password: '',
})

const rules = reactive<Rules>({
    phoneNumber: [
        {
            required: true,
            message: '请输入账号',
            type: 'string'
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            type: 'string'
        },
    ]
})

//调用后台接口，完成登录
// TODO 这里密码是明文发送的会有安全问题啊
import { userLoginService } from '@/api/user'
const login = async () => {
    let result = await userLoginService(formInline);
    ElMessage({
            showClose: true,
            message: result.msg ? result.msg : '登录成功',
            type: 'success',
    })
    //TODO 测试用，在控制台输出
    console.log(result);
    return result;
}

const onSubmit = () => {
    console.log('submit!')
    formRef.value?.validate(async (validate: any) => {
        if (validate) {

            let result = await login();
            //TODO 测试输出
            // console.log("登录" + result.data);
            
            console.log('登录成功');

            //保存token到 localStorage
            localStorage.setItem('token', result.data)

            //保存token到pinia,之后想使用的话可以使用
            tokenStore.setToken(result.data)

            // 把token存入cookie，为了SSE的时候使用
            document.cookie = `token=${tokenStore.token}; path=/; max-age=3600`;

            //输出到控制台看一下
            // console.log("pinia登录" + tokenStore.token);

            //调用后台接口获取用户信息
            let userInfo = await getUserInfoService(result.data);

            //将用户信息放进pinia中以便以后使用
            userStore.setUid(userInfo.data.uid)
            userStore.setUserType( userInfo.data.userType )
            userStore.setPassword( userInfo.data.password )
            userStore.setNickname( userInfo.data.nickname )
            userStore.setPhoneNumber( userInfo.data.phoneNumber )
            userStore.setGender( userInfo.data.gender )
            userStore.setIntroduction( userInfo.data.introduction )
            userStore.setCreateTime( userInfo.data.createTime )
            userStore.setUpdateTime( userInfo.data.updateTime )

            //输出看一下
            console.log("用户信息Store" + userStore.user.uid);

            // 根据其中的userType来判断跳转到不同页面
            //如果是admin就跳转到/admin，如果是user就跳转到/home
            if (userInfo.data.userType == 'admin') {
                router.push('/admin')
            }else{
                router.push('/home')
            }
            
        } else {
            ElMessage({
                showClose: true,
                message: '请输入账号和密码',
                type: 'error',
            })
            console.log('error!')
        }
    })
}

//注册按钮:转跳到注册页面
const toRegister = () => {
    router.push('/register')
}

// const test = () => {
//     c.value = c.value + 1;
// }

const formRef = ref<FormInstance>()
</script>

<template>
    <el-card class="LoginCard" style="max-width: 480px">
        <template #header>
            <div class="card-header">
                <span>基于鸟鸣声的鸟类识别系统</span>
            </div>
        </template>
        <div>
            <el-form ref="formRef" :rules="rules" :inline="false" :model="formInline" class="demo-form-inline">
                <el-form-item label="账号（手机号）" prop="phoneNumber">
                    <el-input v-model="formInline.phoneNumber" placeholder="请输入账号" clearable />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="formInline.password" type="password" placeholder="请输入密码" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">Login</el-button>
                    <el-button type="primary" @click="toRegister">toRegister</el-button>
                    <!-- <el-button type="primary" @click="test">test</el-button> -->
                </el-form-item>
                <el-form-item>
                    <p>PS：任意11位数字即可注册（只要不和系统内已有的重复就可以）</p>
                </el-form-item>
            </el-form>
        </div>
    </el-card>
</template>

<style scoped>
.LoginCard {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}
.demo-form-inline {
    --el-input-width: 220px;
    margin: 20px;
}

.el-input {
    --el-input-width: 220px;
}

.button-group {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>